﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Xml;

namespace HuaXingSDK
{
    public abstract class XmlToEntity
    {
        protected XmlDocument Xml { get; }

        protected XmlToEntity(string outerXml)
        {
            Xml = new XmlDocument();
            Xml.LoadXml(outerXml);
            LoadFromXml();
        }

        private void LoadFromXml()
        {
            var root = Xml.DocumentElement;

            if (root == null)
                throw new HXException("没有根节点。");

            foreach (var node in root.ChildNodes.ToArray())
            {
                if (!string.IsNullOrEmpty(node.InnerXml))
                {
                    SetValue(node);
                }
            }
        }

        protected virtual void SetValue(XmlNode xmlNode)
        {
            var p = GetType().GetProperty(xmlNode.Name, BindingFlags.IgnoreCase | 
                BindingFlags.Instance | BindingFlags.Public);

            var value = GetValue(p.PropertyType, xmlNode);

            if (value != null)
            {
                p.SetValue(this, value, null);
            }
        }

        protected virtual object GetValue(Type propertyType, XmlNode node)
        {
            if (string.IsNullOrEmpty(node.InnerXml))
                return null;

            var pt = propertyType;

            if (pt == typeof(string) && !string.IsNullOrEmpty(node.InnerText))
            {
                return node.InnerText;
            }
            if (pt == typeof(int) && !string.IsNullOrEmpty(node.InnerText))
            {
                return Convert.ToInt32(node.InnerText);
            }
            if (pt == typeof(long) && !string.IsNullOrEmpty(node.InnerText))
            {
                return Convert.ToInt64(node.InnerText);
            }
            if (pt == typeof(decimal) && !string.IsNullOrEmpty(node.InnerText))
            {
                return Convert.ToDecimal(node.InnerText);
            }
            if (pt == typeof(bool) && !string.IsNullOrEmpty(node.InnerText))
            {
                var b = node.InnerText.ToLower().Trim();
                return b == "0" || b == "true";
            }
            if (pt.IsEnum && !string.IsNullOrEmpty(node.InnerText))
            {
                int num;
                if (int.TryParse(node.InnerText, out num) == false && node.InnerText.Length == 1)
                {
                    num = node.InnerText[0];
                }
                return Enum.Parse(pt, num.ToString());
            }

            return null;
        }
    }
}
